package com.example.service.impl;

import com.example.exception.BusinessException;
import com.example.mapper.UserMapper;
import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.service.LoginService;
import com.example.utils.DbUtil;
import com.example.utils.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class LoginServiceImpl implements LoginService {

    private static String appId = "wx000d33f30b934fa7";

    private static String secret = "9557ff1543a25fa85b339620a5a5e261";

//    网络请求的模板类
    @Resource
    private RestTemplate restTemplate;

    @Resource
    private UserMapper userMapper;

    @Override
    public Result login(String code) {
        //用登录凭证换取登录信息
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                    + appId + "&secret="
                    + secret + "&js_code=" +
                    code + "&grant_type=authorization_code";
            String response = restTemplate.getForObject(url, String.class);
            //把json字符串解析为map
            ObjectMapper objectMapper = new ObjectMapper();
            HashMap hashMap = objectMapper.readValue(response, HashMap.class);
            //获取微信用户的 openid
            String openid = (String) hashMap.get("openid");

            //绑定用户信息
            User user = userMapper.findUserByOpenId(openid);
            if(user == null){
                //如果第一次登录，则创建用户信息
                user = new User();
                user.setName("微信用户"+ UUID.randomUUID().toString().substring(0,6));
                user.setOpenid(openid);
                user.setCreateTime(LocalDateTime.now());
                int saveResult = userMapper.insert(user);
                if(saveResult <= 0){
                    throw new BusinessException(500,"用户注册失败");
                }
            }


            //生产jwt 令牌
            String token = JwtUtil.generateToken(openid);
            //返回给前端
            HashMap result = new HashMap<>();
            result.put("token",token);
            return Result.success(result);
        } catch (IOException e) {
            throw new BusinessException(500,"微信登录信息解析错误",e);
        }
    }
    @Override
    public Result getUserCredit(String token) {
//从jwt中获取用户的openId
        String openId = JwtUtil.getOpenIdByToken(token);
//模拟数据库的查询操作
        ConcurrentHashMap<String, User> userTable = DbUtil.userTable;
//用openId获取用户信息
        User user = userTable.get(openId);
//返回成功的响应结果给前端
        return  Result.success(user);
    }
}
